package com.qf.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.qf.pojo.DtsCategory;
import com.qf.service.CategoryService;
import com.qf.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author fy
 * @version V1.0
 * @Project workspace
 * @Package com.qf.controller
 * @Description:
 * @Date 2022/6/21 23:21
 */
@RestController
@CrossOrigin("*")
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    //http://localhost:8083/admin/category/list?page=1&limit=20
    // &id=1&name=xx
    // &sort=add_time&order=desc
    @GetMapping("/list")
    public Object queryCategory(Integer id, String name,
                                @RequestParam(defaultValue = "1") Integer page,
                                @RequestParam(defaultValue = "20") Integer limit,
                                @RequestParam(defaultValue = "add_time") String sort,
                                @RequestParam(defaultValue = "desc") String order ){
        IPage<DtsCategory> iPage = categoryService.queryCategoryPage(id, name, page, limit, sort, order);
        //获取结果集
        List<DtsCategory> list = iPage.getRecords();
        //查询总条数
        long total = iPage.getTotal();
        //封装对象返回
        Map<String,Object> data = new HashMap<>();
        data.put("total", total);
        data.put("items", list);
        return ResponseUtil.ok(data);
    }

    @GetMapping("/l1")
    public Object L1(){
        List<DtsCategory> list = categoryService.categoryList1();
        List<Map<String,Object>> data = new ArrayList<>();
        for (DtsCategory category : list) {
            Map<String,Object> map = new HashMap<>();
            map.put("value", category.getId());
            map.put("label", category.getName());
            data.add(map);
        }
        return ResponseUtil.ok(data);
    }

    @PostMapping("/create")
    public Object create(@RequestBody DtsCategory category){
        DtsCategory dtsCategory = categoryService.add(category);
        return ResponseUtil.ok(dtsCategory);
    }

    @PostMapping("/update")
    public Object update(@RequestBody DtsCategory category){
        int count = categoryService.update(category);
        if (count == 0){
            return ResponseUtil.fail();
        }
        return ResponseUtil.ok(category);
    }

    @PostMapping("/delete")
    public Object delete(@RequestBody DtsCategory category){
        categoryService.delete(category.getId());
        return ResponseUtil.ok();
    }

}
